//
//  RecVideoMoreViewController.swift
//

import UIKit

class RecVideoMoreViewController: BaseViewController {

    var navTitle: String = ""
    var id: String = ""
    var atype: String = ""
    var layoutType: LayoutType = .video
    private var resuleModel = RecChildDataModel()
    private var page: Int = 1
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = space
        layout.minimumInteritemSpacing = 10.fit
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.sysTableView
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(RecCell.self)
        collectionView.register(RecBigListCell.self)
        collectionView.register(RecBannerCell.self)
        collectionView.register(RecSlideCell.self)
        collectionView.register(RecHeaderItemCell.self)
        collectionView.register(RecStoreCell.self)
        collectionView.register(RecStoreListCell.self)
        return collectionView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNav()
        addSubviews()
    }
    
    private func setupNav() {
        navigation.item.title = navTitle
    }

    private func addSubviews() {
        
        disablesAdjustScrollViewInsets(collectionView)
        
        view.addSubview(collectionView)
        
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(topLayoutGuideBottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(safeAreaLayoutGuideBottom)
        }
        
        collectionView.mj_headerRefresh { [weak self] in
            guard let `self` = self else { return }
            switch self.layoutType {
            case .slide, .book:
                self.requestBookData()
            case .store, .store_list:
                self.requestStoresData()
            default:
                self.requestVideoData()
            }
        }
        
        switch self.layoutType {
        case .slide, .book:
            break
        case .store, .store_list:
            collectionView.mj_footerRefresh { [weak self] in
                guard let `self` = self else { return }
                self.page += 1
                self.requestStoresData()
            }
        default:
            collectionView.mj_footerRefresh { [weak self] in
                guard let `self` = self else { return }
                self.page += 1
                self.requestVideoData()
            }
        }
        
        collectionView.beginRefreshing()
    }
}

extension RecVideoMoreViewController {
    
    private func requestVideoData() {
        Network.Rec
            .videos(id: id, page: page)
            .request()
            .responseData(RecChildDataModel.self) { [weak self] (model) in
                guard let `self` = self else { return }
                self.collectionView.endHeaderRefresh()
                self.collectionView.endFooterRefresh()
                if self.collectionView.isHeaderRefresh {
                    self.resuleModel = model.result
                    self.resuleModel.items.removeAll()
                }
                self.resuleModel.items.append(contentsOf: model.result.items)
                self.collectionView.reloadData()
        } failure: { [weak self] (error) in
            guard let `self` = self else { return }
            Toast.show(info: error.errorMessage)
            self.collectionView.endHeaderRefresh()
            self.collectionView.endFooterRefresh()
        }
    }
    
    private func requestBookData() {
        Network.Rec
            .books(id: id)
            .request()
            .responseData(RecChildModel.self) { [weak self] (model) in
                guard let `self` = self else { return }
                self.collectionView.endHeaderRefresh()
                if self.collectionView.isHeaderRefresh {
                    self.resuleModel = model.result.data
                    self.resuleModel.items.removeAll()
                }
                self.resuleModel.items.append(contentsOf: model.result.data.items)
                self.collectionView.reloadData()
        } failure: { [weak self] (error) in
            guard let `self` = self else { return }
            Toast.show(info: error.errorMessage)
            self.collectionView.endHeaderRefresh()
        }
    }
    
    private func requestStoresData() {
        Network.Rec
            .stores(id: id, page: page)
            .request()
            .responseData(RecChildDataModel.self) { [weak self] (model) in
                guard let `self` = self else { return }
                self.collectionView.endHeaderRefresh()
                self.collectionView.endFooterRefresh()
                if self.collectionView.isHeaderRefresh {
                    self.resuleModel = model.result
                    self.resuleModel.items.removeAll()
                }
                self.resuleModel.items.append(contentsOf: model.result.items)
                self.collectionView.reloadData()
        } failure: { [weak self] (error) in
            guard let `self` = self else { return }
            Toast.show(info: error.errorMessage)
            self.collectionView.endHeaderRefresh()
            self.collectionView.endFooterRefresh()
        }
    }
}

extension RecVideoMoreViewController: UICollectionViewDelegate, UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return resuleModel.items.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let model = resuleModel.items[indexPath.item]
        switch layoutType {
        case .big:
            let cell = collectionView.dequeueReusableCell(withClass: RecCell.self, for: indexPath)
            cell.update(big: model)
            return cell
        case .big_list:
            let cell = collectionView.dequeueReusableCell(withClass: RecBigListCell.self, for: indexPath)
            cell.update(model)
            return cell
        case .book, .slide:
            let cell = collectionView.dequeueReusableCell(withClass: RecBigListCell.self, for: indexPath)
            cell.update(slide: model)
            return cell
        case .store, .store_list:
            let cell = collectionView.dequeueReusableCell(withClass: RecStoreListCell.self, for: indexPath)
            cell.update(list: model)
            return cell
        default:
            let cell = collectionView.dequeueReusableCell(withClass: RecCell.self, for: indexPath)
            cell.update(model)
            return cell
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = resuleModel.items[indexPath.item]
        switch layoutType {
        case .video, .hot:
            let vc = PlayerViewController(url: model.url, id: model.subcateid)
            push(vc)
            for (index, _) in resuleModel.items.enumerated() {
                resuleModel.items[index].isSelected = false
            }
            resuleModel.items[indexPath.item].isSelected = true
            VideoCacheManager.share.setVideo(resuleModel, forKey: resuleModel.subcateid)
        case .store, .store_list, .audio_list:
            let vc = RecAudioListViewController()
            vc.id = model.albumId
            vc.atype = atype
            vc.outerid = model.id
            push(vc)
        case .book:
            Toast.maskLoading()
            
            for (index, _) in resuleModel.items.enumerated() {
                resuleModel.items[index].isSelected = false
            }
            resuleModel.items[indexPath.item].isSelected = true
            BookCacheManager.share.setBook(resuleModel, forKey: resuleModel.id)
            
            ZipManager.share
                .downloadZipHandler(model.url) { progress in
                    debugPrint("下载进度: \(progress)")
            } unzipProgress: { progress in
                debugPrint("解压进度: \(progress)")
            } response: { bookModel in
                Toast.hide()
                if let model = bookModel {
                    let vc = ReadBookViewController(bookModel: model)
                    self.push(vc)
                } else {
                    Toast.show(info: "数据解析失败")
                }
            } failure: { error in
                Toast.show(info: error.errorMessage)
            }
        default:
            break
        }
    }
}

extension RecVideoMoreViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        switch layoutType {
        case .big:
            let width = UIScreen.width - space * 2
            return CGSize(width: width, height: width * 9 / 16 + 25.fit)
        case .big_list:
            let width = UIScreen.width - space * 2
            return CGSize(width: width, height: width * 8 / 23)
        case .book, .slide:
            let width = (UIScreen.width - space * 4) / 3
            return CGSize(width: width, height: width * 5 / 4)
        case .store, .store_list:
            let height = (UIScreen.width - space * 4) / 3
            return CGSize(width: UIScreen.width - space, height: height)
        default:
            let width = (UIScreen.width - space * 3) / 2
            return CGSize(width: width, height: width * 9 / 16 + 25.fit)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        switch layoutType {
        case .store, .store_list:
            return UIEdgeInsets(top: 10.fit, left: space, bottom: 10.fit, right: 0)
        default:
            return UIEdgeInsets(top: 10.fit, left: space, bottom: 10.fit, right: space)
        }
    }

}
